<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * Return a new JSON response from the application.
     *
     * @param  mixed  $data
     * @param  string  $message
     * @param  int  $code
     * @param  array  $headers
     * @param  int  $options
     * @return JsonResponse
     */

    protected function response($data = [], $message = '', $code = 200, array $headers = [], $options = 0)
    {
        if ($code >= 400 && $code <= 499) {// client error
            $status = 'error';
        } elseif ($code >= 500 && $code <= 599) {// service error
            $status = 'fail';
        } else {
            $status = 'success';
        }

        if ($data instanceof AbstractPaginator) {
            $paginated = $data->toArray();
            $hasmore = $paginated['current_page'] > 0 && $paginated['current_page'] > $paginated['last_page'];
            return new JsonResponse([
                'status' => $status,
                'code' => $code,
                'message' => $message,
                'total' => $paginated['total'] ?? 0,
                'count' => $paginated['to'] ?? 0,
                'per_page' => $paginated['per_page'] ?? 0,
                'current_page' => $paginated['current_page'] ?? 0,
                'total_pages' => $paginated['last_page'] ?? 0,
                'data' => $paginated['data'],
                'hasmore' => $hasmore

            ], $code, $headers, $options);
        }

        return new JsonResponse([
            'status' => $status,
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ], $code, $headers, $options);
    }
}
